package appController

import (
	"CMETO/models"
	"CMETO/utils"
	"CMETO/utils/jwt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// app部分的接口
type OrderController struct{}

// @Summary 订单查询
// @Description 查订单
// @Tags APP管理
// @Accept json
// @Produce json
// @Success 200 {object} models.ResultCommon[[]models.Order] "查询成功"
// @Success 401 {object} models.ResultCommon[string] "查询失败"
// @Router /app/order [get]
// @Security JWT
func (r OrderController) QueryOrders(ctx *gin.Context) {
	token, _ := ctx.Get("token")
	id := token.(*jwt.MyClaims).User.Id
	var order []models.Order
	err := models.DB.Where("customer_id = ?", id).Find(&order).Error
	if err != nil {
		ctx.JSON(http.StatusOK, models.ResultCommon[string]{
			Msg:    "查询失败",
			Code:   "400",
			Result: "",
		})
	} else {
		ctx.JSON(http.StatusOK, models.ResultCommon[[]models.Order]{
			Msg:    "查询成功",
			Code:   "200",
			Result: order,
		})
	}
}

// @Summary 订单新增
// @Description 新增订单
// @Tags 订单管理
// @Accept json
// @Produce json
// @Param deptInfo body models.Order true "订单信息"
// @Success 200 {object} models.AddResult "新增成功"
// @fail 400 {object} models.ErrorResult "数据错误"
// @fail 401 {object} models.AddResult "新增失败"
// @Router /app/order [post]
// @Security JWT
func (d OrderController) AddOrder(ctx *gin.Context) {
	order := &models.Order{}
	// 绑定json数据
	if err := ctx.ShouldBindJSON(&order); err != nil {
		ctx.JSON(http.StatusOK, &models.ErrorResult{
			Msg:    "数据错误",
			Code:   "400",
			Result: nil,
		})
	} else {
		order.CreateTime = utils.TimeFormatter(time.Now())
		result := models.DB.Model(&order).Create(&order).Error
		if result != nil {
			ctx.JSON(http.StatusOK, &models.AddResult{
				Msg:    "新增失败",
				Code:   "400",
				Result: 0,
			})
		} else {
			ctx.JSON(http.StatusOK, &models.AddResult{
				Msg:    "新增成功",
				Code:   "200",
				Result: 1,
			})
		}
	}
}
